<template>
  <page-layout title="参保人管理">
    <a-card>
      <div>
        <div class="board_div">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="12" v-for="(item, index) in boardDatas" :key="index">
              <div class="gutter-box board dsp_flex">
                <div class="dsp_flex item_div_wrapper" v-for="(i, index) of item" :key="index">
                  <div class="item_div dsp_flex">
                    <img class="icon" :src="i.txt | iconTypeFilter" alt="" />
                    <div class="box_wrapper first_box dsp_flex resetFlex_align">
                      <p>{{i.txt}}</p>
                      <p>{{i.total | totalFilter}}</p>
                      <p :class="i.totalPrecent ? '' : 'hide'">
                        <span class="percent_span" :class="i.totalPrecent > 0 ? 'upTriangle' : 'downTriangle'">{{i.totalPrecent | precentFilter}}%</span>
                      </p>
                      <p :class="i.totalPrecent ? '' : 'hide'">同比上月{{i.totalPrecent > 0 ? '增加' : '降低'}}{{Math.round(Math.abs(i.totalPrecent)*100)}}%</p>
                    </div>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>

        <div class="search_div">
          <a-row type="flex" justify="center" align="middle" class="topSearch_row">
            <a-col :span="24">
              <a-form :model="iptform" ref="iptform" layout="inline" labelAlign="left">
                <a-form-item label="关键字">
                  <a-input allow-clear placeholder="请输入姓名/身份证号" v-model="iptform.nameIdVal" :style="widthReset" />
                </a-form-item>
                <a-form-item label="城市">
                  <Vcity class="cbr_cityTem" before="" :citydata="cityData" @selectDepCityFn="selectDepCity" :style="widthReset" />
                </a-form-item>
                <a-form-item label="社保状态" class="socialSecurity_label">
                  <a-select allow-clear show-search option-filter-prop="children" v-model="iptform.socialSecurityVal" placeholder="请选择社保状态" :style="widthReset">
                    <a-select-option v-for="item in selectDataArr" :key="item.key">
                      {{item.value}}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="公积金状态">
                  <a-select allow-clear show-search option-filter-prop="children" v-model="iptform.providentFundVal" placeholder="请选择公积金状态" :style="widthReset">
                    <a-select-option v-for="item in selectDataArr" :key="item.key">
                      {{item.value}}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="项目名称" class="proName_label">
                  <a-select allow-clear show-search option-filter-prop="children" v-model="iptform.proNameVal" placeholder="请选择项目名称" @focus="proNameFocusFn" :style="widthReset">
                    <a-select-option v-for="(value, key) in proNameDataObj" :key="key">
                      {{value}}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="供应商名称">
                  <a-select allow-clear show-search option-filter-prop="children" v-model="iptform.supplierNameVal" placeholder="请选择供应商名称" @focus="supplierFocusFn" :style="widthReset">
                    <a-select-option v-for="item in supplierNameArr" :key="item.id">
                      {{item.fullName}}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="searchBtnClkFn">
                    <a-icon type="search" />查询
                  </a-button>
                </a-form-item>
              </a-form>
            </a-col>

            <a-col :span="24" class="mt_20">
              <a-space>
                <a-button type="primary" @click="exportBtnClkFn" icon="upload" :loading="btnLoading">参保人档案导出</a-button>
                <a-button @click="batchTjBtnClkFn">批量调基</a-button>
                <a-button @click="batchBjBtnClkFn">批量补缴</a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>

        <div class="table">
          <advance-table :columnsResetIsShow="false" :columns="columns" :scroll="tableData.length > 0 ? { x: 1500 } : undefined" :data-source="tableData" title=" " :loading="loading" rowKey="id" @search="onSearch" @refresh="onRefresh" :format-conditions="true" @reset="onReset" :pagination="{
        current: page,
        pageSize: pageSize,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: onPageChange,
        onShowSizeChange: onSizeChange,
      }">
            <template slot="name" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{text.text}}
                </template>
                {{text.text ? text.text : '-' | nameFilter}}
              </a-tooltip>
            </template>

            <template v-for="col in ['projectName','idCard', 'cityName', 'supplierName', 'registerType', 'socialPolicyName', 'fundPolicyName', 'socialBaseAmt']" :slot="col" slot-scope="text">
              {{text.text ? text.text : '-'}}
            </template>
            <template slot="socialArchivesStatus" slot-scope="text">
              <a-tag v-if="text.text" :color="colorFilter(text.text)">
                {{text.text | statusFilter}}
              </a-tag>
              <span v-else>{{text.text | statusFilter}}</span>
            </template>
            <template slot="fundArchivesStatus" slot-scope="text">
              <a-tag v-if="text.text" :color="colorFilter(text.text)">
                {{text.text | statusFilter}}
              </a-tag>
              <span v-else>{{text.text | statusFilter}}</span>
            </template>
            <template slot="status" slot-scope="text">
              <a-tag v-if="text.text" :color="colorFilter(text.text)">
                {{text.text | statusFilter}}
              </a-tag>
              <span v-else>{{text.text | statusFilter}}</span>
            </template>
            <template slot="opera" slot-scope="text">
              <a @click="goDetails(text)">详情</a>
            </template>
          </advance-table>
        </div>

        <!-- 详情drawer -->
        <detailDrawer class="detail_drawer" :title="'社保公积金详情'" @cancelDrawer="cancelDrawer" :visible.sync="drawerVisible">
          <socialDetail slot="content" :id="userId"></socialDetail>
        </detailDrawer>

        <!-- 批量导入 -->
        <a-modal :class="isDisable ? 'disable' : ''" :visible="resultModalShow" :title="'批量'+titleName+'导入'" ok-text="下一步" @ok="onNext" @cancel="handleCancel" width="960px" :bodyStyle="{ height: '626px' }">
          <a-steps class="steps" :current="current">
            <a-step title="上传文件" description="导入数据" />
            <a-step title="执行导入" description="数据导入至服务器" />
            <a-step title="导入成功" description="完成数据批量导入" />
          </a-steps>
          <div class="content">
            <steps1 v-if="current === 1" @fileUrl="onFileUrl" :resultModal="resultModalShow">
              <template slot="official" v-if="titleName=='补缴'">
                <h3 style="font-weight: 550; margin-bottom: 20px">1. 在列表页导出参保人档案：</h3>
                <p>在导出数据中后2列 社保需补缴月份/ 公积金需补缴月份 中输入需补缴月份，多个月份之间用、隔开，如202106、202107
                  <br />注意：只有“在缴”状态可以进行补缴
                </p>
                <h3 style="font-weight: 550; margin-bottom: 20px">2. 维护好后导入：导入完成后系统会自动生成对应补缴待办</h3>
              </template>
              <template slot="official" v-if="titleName=='调基'">
                <h3 style="font-weight: 550; margin-bottom: 20px">1. 在列表页导出参保人档案：</h3>
                <p>在导出数据中后2列 调整后社保基数/调整后公积金基数中输入新参数，如4000
                  <br />注意：只有“在缴”状态可以进行调基
                </p>
                <h3 style="font-weight: 550; margin-bottom: 20px">2. 维护好后导入：导入完成后系统会自动生成对应调基待办，待办完成后雇员档案基数会自动修改</h3>
              </template>
            </steps1>
            <steps2 v-if="current === 2" @importSuccess="onImportSuccess"></steps2>
            <steps3 v-if="current === 3" :fileUrl="failFileUrl" :unAbnormalTotal="unAbnormalTotal" :abnormalTotal="abnormalTotal"></steps3>
          </div>
          <template slot="footer" v-if="current == 3">
            <a-button @click="handleCancel"> 取消 </a-button>
            <a-button type="primary" @click="onImport">
              继续导入
            </a-button>
            <a-button type="primary" @click="onStepSure">
              确定
            </a-button>
          </template>
        </a-modal>

      </div>
    </a-card>
  </page-layout>
</template>
  
<script>
import Vcity from '@/components/vcity/index'
import AdvanceTable from '@/components/table/advance/AdvanceTable'
import datas from '@/utils/data'
import { splitK } from '@/utils/util'
import securityIcon from '@/assets/img/socialSecurityFund/security.png'
import sccFundIcon from '@/assets/img/socialSecurityFund/sccFund.png'
import addIcon from '@/assets/img/socialSecurityFund/plus.png'
import reduceIcon from '@/assets/img/socialSecurityFund/down.png'
import detailDrawer from '@/pages/components/drawer'
import socialDetail from '@/pages/socialSecurityFund/socialSecurityFundDetail'
import steps1 from "@/pages/components/increasedWorkers/steps/steps1"
import steps2 from "@/pages/components/increasedWorkers/steps/steps2"
import steps3 from "@/pages/components/increasedWorkers/steps/steps3"
import PageLayout from "@/layouts/PageLayout"
import { mapState, mapMutations } from 'vuex'
import { pageSocialListApi, getAllCityApi, proNameBaseSelectApi, findSupplierInfoApi, insuredCountApi, exportEmployeeSocialApi, batchCreateOrderApi, batchCreateOrderbjApi } from '@/services/socialSecurityFund'


/**
 * @description: 百分比转小数
 * @param {*}
 * @return {*}
 */
function toPoint (percent) {
  if (percent) {
    if (String(percent).indexOf("%") != -1) {
      var str = percent.replace("%", "");
      str = str / 100;
      return str;
    } else {
      return percent / 100;
    }
  } else {
    return '-'
  }
}

export default {
  name: 'tab1',
  components: { AdvanceTable, Vcity, detailDrawer, socialDetail, steps1, steps2, steps3, PageLayout },
  filters: {
    precentFilter (n) {
      let _n = Number(n)
      if (!isNaN(_n)) {
        if (_n < 0) {
          return Math.round(Math.abs(_n) * 100)
        } else {
          return Math.round(_n * 100)
        }
      } else {
        return '-'
      }
    },

    iconTypeFilter (type) {
      if (type == '社保在缴') {
        return securityIcon
      } else if (type == '公积金在缴') {
        return sccFundIcon
      } else if (type == '当月增员') {
        return addIcon
      } else {
        return reduceIcon
      }
    },

    totalFilter (num) {
      if (num) {
        return splitK(num)
      } else {
        return 0
      }
    },

    statusFilter (str) {
      switch (str) {
        case 'adding':
          return '增员中'
        case 'cutting':
          return '减员中'
        case 'online':
          return '在缴'
        case 'offline':
          return '不在缴'
        case 'UnEntry':
          return '待入职'
        case 'OnJob':
          return '在职'
        case 'UnDimission':
          return '待离职'
        case 'Dimission':
          return '已离职'
        case 'Expired':
          return '已失效'
        case 'creating':
          return '待创建'
        default:
          return '-'
      }
    },

    nameFilter (name) {
      return name.length > 4 ? name.substring(0, 4) + '...' : name
    }
  },
  computed: {
    boardDatas () {
      let {
        currMonthSocialOnlineCount,// 当月社保在缴
        currMonthSocialAddingCount,// 当月增员
        currMonthSocialCutingCount,// 当月减员
        currMonthFundOnlineCount,// 当月公积金在缴
        currMonthFundAddingCount,// 当月增员
        currMonthFundCutingCount,// 当月减员
        tbsySocialOnlinePercent,// 当月社保在缴同比上月 (正数是增加，负数是降低)
        tbsySocialAddingPercent,// 当月增员同比上月
        tbsySocialCutingPercent,// 当月减员同比上月
        tbsyFundOnlinePercent,// 当月公积金在缴同比上月
        tbsyFundAddingPercent,// 当月增员同比上月
        tbsyFundCutingPercent, // 当月减员同比上月
        socialOnlineCount, // 社保在缴总数
        fundOnlineCount // 公积金在缴总数
      } = this.topCountData

      let boardDatasObj = {
        socialSecurityData: [
          {
            txt: '社保在缴',
            total: socialOnlineCount, //  currMonthSocialOnlineCount
            // totalPrecent: toPoint(tbsySocialOnlinePercent)
          },
          {
            txt: '当月增员',
            total: currMonthSocialAddingCount,
            totalPrecent: toPoint(tbsySocialAddingPercent)
          },
          {
            txt: '当月减员',
            total: currMonthSocialCutingCount,
            totalPrecent: toPoint(tbsySocialCutingPercent)
          },
        ],
        sccFundData: [
          {
            txt: '公积金在缴',
            total: fundOnlineCount, // currMonthFundOnlineCount
            // totalPrecent: toPoint(tbsyFundOnlinePercent)
          },
          {
            txt: '当月增员',
            total: currMonthFundAddingCount,
            totalPrecent: toPoint(tbsyFundAddingPercent)
          },
          {
            txt: '当月减员',
            total: currMonthFundCutingCount,
            totalPrecent: toPoint(tbsyFundCutingPercent)
          },
        ],
      }
      return boardDatasObj
    },

    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', ['lang']),
  },
  data () {
    return {
      iptform: {
        nameIdVal: '',
        socialSecurityVal: undefined,
        providentFundVal: undefined,
        proNameVal: undefined,
        cityId: null,
        supplierNameVal: undefined
      },
      columns: datas.socialSecurityFundListColumns,
      tableData: [],
      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,
      selectWidth: 'width: 100%',
      selectDataArr: datas.cbrSelectData,
      cityData: [],
      proNameDataObj: {},
      supplierNameArr: [],
      topCountData: {},
      btnLoading: false,
      userId: null,
      resultModalShow: false,
      current: 1,
      fileUrl: '',
      unAbnormalTotal: "",
      abnormalTotal: "",
      failFileUrl: null,
      titleName: '',
      isDisable: true,
      widthReset: 'width: 202.5px;',
      drawerVisible: false
    }
  },
  created () {
    this.getList()
    this.getCityIvk()
    this.insuredCountIvk()
  },
  methods: {
    ...mapMutations('setting', ['setShowDrawer']),

    cancelDrawer () {
      // this.setShowDrawer(false)
      this.drawerVisible = false
    },

    insuredCountIvk () {
      insuredCountApi().then(res => {
        let { code, data, msg } = res.data
        if (code === 200) {
          this.topCountData = data
        } else {
          this.$message.error(msg)
        }
      })
    },

    getList () {
      let {
        cityId,
        nameIdVal,
        proNameVal,
        providentFundVal,
        socialSecurityVal,
        supplierNameVal,
      } = this.iptform

      let params = {
        keyword: nameIdVal,
        pageNum: this.page,
        pageSize: this.pageSize,
        socialStatus: socialSecurityVal,
        fundStatus: providentFundVal,
        socialCityId: cityId,
        projectId: proNameVal,
        supplierId: supplierNameVal
      }

      this.loading = true
      pageSocialListApi(params).then(res => {
        this.loading = false
        let { code, msg, data } = res.data
        if (code === 200) {
          this.tableData = data.content
          this.page = data.pageNum
          this.pageSize = data.pageSize
          this.total = data.totalElements
        } else {
          this.$message.error(msg)
        }
      })
    },

    getCityIvk () {
      getAllCityApi().then(res => {
        let { code, data, msg } = res.data
        if (code === 200) {
          this.cityData = data
        } else {
          this.$message.error(msg)
        }
      })
    },

    proNameFocusFn () {
      proNameBaseSelectApi().then(res => {
        let { code, data, msg } = res.data
        if (code === 200) {
          this.proNameDataObj = data.project
        } else {
          this.$message.error(msg)
        }
      })
    },

    supplierFocusFn () {
      findSupplierInfoApi().then(res => {
        let { code, data, msg } = res.data
        if (code === 200) {
          this.supplierNameArr = data
        } else {
          this.$message.error(msg)
        }
      })
    },

    searchBtnClkFn () {
      this.getList()
    },

    onSearch (conditions, searchOptions) {
      this.page = 1
      this.conditions = conditions
    },

    onSizeChange (current, size) {
      this.page = 1
      this.pageSize = size
      this.getList()
    },

    onRefresh (conditions) {
      this.conditions = conditions
    },

    onReset (conditions) {
      this.conditions = conditions
    },

    onPageChange (page, pageSize) {
      this.page = page
      this.pageSize = pageSize
      this.getList()
    },

    goDetails (text) {
      this.userId = text.record.id
      this.$Storage.set('serveLogVal', text.record.id)
      // this.setShowDrawer(true)
      this.drawerVisible = true
    },

    selectDepCity (data) {
      this.iptform.cityId = data.id
    },

    exportBtnClkFn () {
      let {
        cityId,
        nameIdVal,
        proNameVal,
        providentFundVal,
        socialSecurityVal,
        supplierNameVal,
      } = this.iptform

      let params = {
        keyword: nameIdVal,
        socialStatus: socialSecurityVal,
        fundStatus: providentFundVal,
        socialCityId: cityId,
        projectId: proNameVal,
        supplierId: supplierNameVal
      }
      this.btnLoading = true
      exportEmployeeSocialApi(params).then(res => {
        this.btnLoading = false

        let { code, msg, data } = res.data
        if (code === 200) {
          window.location.href = data
        } else {
          this.$message.error(msg)
        }
      })
    },

    batchTjBtnClkFn () {
      this.resultModalShow = true
      this.titleName = '调基'
      this.fileUrl = ''
      this.current = 1
      this.isDisable = true
    },

    batchBjBtnClkFn () {
      this.resultModalShow = true
      this.titleName = '补缴'
      this.fileUrl = ''
      this.current = 1
      this.isDisable = true
    },

    onNext () {
      if (this.current == 1) {
        if (!this.fileUrl) {
          this.$message.warning('请选择上传文件！');
          return;
        }

        if (this.titleName == '调基') {
          this.batchImportIvk(1, { fileUrl: this.fileUrl });  // 批量调基    
          this.isDisable = true
        } else {
          this.batchImportIvk(2, { fileUrl: this.fileUrl }); // 批量补缴
          this.isDisable = true
        }
      }
      this.current = this.current + 1;
    },

    // 批量导入
    batchImportIvk (type, params) {
      let $api = type == 1 ? batchCreateOrderApi : batchCreateOrderbjApi
      $api(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.abnormalTotal = data.fail; // unAbnormalTotal 正常  abnormalTotal 异常
          this.unAbnormalTotal = data.total - data.fail
          this.failFileUrl = data.failFileUrl
          // this.current = this.current + 1;                
        } else {
          this.$message.error(msg);
        }
      })
    },

    handleCancel () {
      this.resultModalShow = false;
      this.current = 1;
    },

    onFileUrl (url) {
      this.fileUrl = url;
      if (url) {
        this.isDisable = false
      }
    },

    onImportSuccess (data) {
      this.current = 2;
      if (data) {
        this.isDisable = false
      }
    },

    onImport () {
      this.current = 1;
      this.fileUrl = ''
      this.isDisable = true
    },

    onStepSure () {
      this.current = 3;
      this.resultModalShow = false;
    },

    colorFilter (type) {
      switch (type) {
        case 'Supplement':
          return 'pink'
        case 'UnEntry':
          return 'orange'
        case 'OnJob':
          return 'blue'
        case 'UnDimission':
          return 'red'
        case 'Dimission':
          return 'red'
        case 'Expired':
          return 'red'
        case 'adding':
          return 'cyan'
        case 'cutting':
          return 'red'
        case 'online':
          return 'green'
        case 'offline':
          return 'purple'
        case 'creating':
          return 'blue'
      }
    }
  }
}
</script>
  
<style scoped lang='less'>
@green: #52c41a;
@red: #f5222d;

.icon {
  width: 36px;
  height: 36px;
  flex-shrink: 0;
  margin: 0 24px 0 14px;
}

.pseudoClass {
  display: block;
  content: "";
  width: 0;
  height: 0;
}

.board {
  padding: 0 10px;
  height: 100px;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 5px;
  justify-content: flex-start;
}

.item_div_wrapper {
  width: 100%;
  justify-content: space-around;
}

.item_div {
  align-items: center;
}

.box_wrapper {
  flex-direction: column;
  align-items: end;
  & > p {
    margin-bottom: 0;
  }
  & > p:not(:nth-of-type(2)) {
    font-size: 12px;
  }
  & > p:nth-of-type(2) {
    font-weight: 700;
    font-size: 18px;
  }
  & > p:first-of-type {
    color: rgba(0, 0, 0, 0.45);
  }
  & > p:last-of-type {
    color: rgba(0, 0, 0, 0.15);
  }
}

.percent_span {
  padding-left: 10px;
}

.downTriangle {
  position: relative;
  color: @red;
  &:before {
    position: absolute;
    left: 0;
    top: 70%;
    transform: translateY(-50%);
    .pseudoClass();
    border: 4px solid rgba(0, 0, 0, 0);
    border-top-color: @red;
  }
}

.upTriangle {
  position: relative;
  color: @green;
  &:before {
    position: absolute;
    left: 0;
    top: 56%;
    transform: translateY(-50%);
    .pseudoClass();
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 5px solid @green;
  }
}

.search_div {
  margin: 20px 0;
  /deep/ .ant-col.ant-col-3 {
    margin-right: 8px;
  }
}

.pl_10 {
  padding-left: 10px;
}

.dsp_flex {
  display: flex;
  display: -webkit-flex;
}

.mt_20 {
  margin-top: 20px;
}

.hide {
  opacity: 0;
  // display: none;
}
.disable {
  /deep/.ant-btn.ant-btn-primary {
    padding: 0;
    line-height: 32px;
    width: 74px;
    opacity: 0.6;
    cursor: default;
    pointer-events: none;
    // cursor: not-allowed;
    span {
      display: block;
      width: 74px;
      height: 32px;
    }
  }
}

.detail_drawer {
  /deep/.ant-drawer-body {
    padding: 0;
  }
}

.resetFlex_align {
  align-items: flex-start;
}

.address_tmp {
  background: #fff !important;
}
</style>